"""
新的产品序列化器 - 集成变体管理
"""

from rest_framework import serializers
from pecco_site.models import (
    Product, ProductTranslation, ProductVariant, ProductVariantImage,
    ProductOption, ProductOptionValue, ProductOptionTranslation,
    ProductOptionValueTranslation, Category, ProductSpecification,
    ProductSpecificationTranslation
)
from decimal import Decimal


class ProductOptionValueNestedSerializer(serializers.ModelSerializer):
    """嵌套的选项值序列化器（包含翻译）"""
    translations = serializers.SerializerMethodField()
    
    class Meta:
        model = ProductOptionValue
        fields = ['id', 'value', 'color_code', 'translations']
    
    def get_translations(self, obj):
        """获取所有语言的翻译"""
        result = {}
        for trans in obj.translations.all():
            result[trans.locale] = trans.value
        # 如果没有翻译，使用默认值
        if not result:
            result['en'] = obj.value
        return result


class ProductOptionNestedSerializer(serializers.ModelSerializer):
    """嵌套的选项类型序列化器（包含翻译和值）"""
    values = ProductOptionValueNestedSerializer(many=True, read_only=True)
    translations = serializers.SerializerMethodField()
    
    class Meta:
        model = ProductOption
        fields = ['id', 'name', 'option_type', 'translations', 'values']
    
    def get_translations(self, obj):
        """获取所有语言的翻译"""
        result = {}
        for trans in obj.translations.all():
            result[trans.locale] = trans.name
        # 如果没有翻译，使用默认值
        if not result:
            result['en'] = obj.name
        return result


class ProductVariantImageSerializer(serializers.ModelSerializer):
    """变体图片序列化器"""
    image_url = serializers.SerializerMethodField()
    
    class Meta:
        model = ProductVariantImage
        fields = ['id', 'image', 'image_url', 'sort_order', 'is_primary']
    
    def get_image_url(self, obj):
        if obj.image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.image.url)
            return obj.image.url
        return None


class ProductSpecificationNestedSerializer(serializers.ModelSerializer):
    """嵌套的规格序列化器"""
    translations = serializers.SerializerMethodField()
    
    class Meta:
        model = ProductSpecification
        fields = ['id', 'spec_key', 'spec_value', 'translations', 'sort_order']
    
    def get_translations(self, obj):
        """获取所有语言的翻译"""
        result = {}
        for trans in obj.translations.all():
            result[trans.locale] = {
                'key': trans.spec_key,
                'value': trans.spec_value
            }
        return result


class ProductVariantDetailSerializer(serializers.ModelSerializer):
    """变体详情序列化器（用于管理后台）"""
    option_values = ProductOptionValueNestedSerializer(many=True, read_only=True)
    option_value_ids = serializers.PrimaryKeyRelatedField(
        many=True, queryset=ProductOptionValue.objects.all(),
        source='option_values', write_only=True, required=False
    )
    images = ProductVariantImageSerializer(many=True, read_only=True)
    specifications = ProductSpecificationNestedSerializer(many=True, read_only=True)

    # 新增字段：价格和库存
    price = serializers.DecimalField(max_digits=10, decimal_places=2, required=False, allow_null=True)
    stock = serializers.IntegerField(required=False, allow_null=True)

    # 新增：选项组合（用于前端显示）
    option_combination = serializers.SerializerMethodField()

    class Meta:
        model = ProductVariant
        fields = [
            'id', 'product', 'option_values', 'option_value_ids', 'sku',
            'product_details', 'is_active', 'sort_order', 'images',
            'specifications', 'price', 'stock', 'option_combination'
        ]

    def get_option_combination(self, obj):
        """获取选项组合的字典形式，例如 {'size': 'Large', 'color': 'Red'}"""
        combination = {}
        for value in obj.option_values.all():
            combination[value.option.option_type] = {
                'id': value.id,
                'value': value.value,
                'color_code': value.color_code
            }
        return combination


class ProductTranslationNestedSerializer(serializers.ModelSerializer):
    """产品翻译序列化器"""
    class Meta:
        model = ProductTranslation
        fields = [
            'locale', 'name', 'short_desc', 'rich_desc',
            'default_product_details', 'general_specifications'
        ]


class ProductDetailNewSerializer(serializers.ModelSerializer):
    """
    新的产品详情序列化器 - 集成所有变体管理功能
    """
    # 分类（简化为 dog/cat）
    category = serializers.SerializerMethodField()
    category_id = serializers.PrimaryKeyRelatedField(
        queryset=Category.objects.all(),
        source='categories', write_only=True, required=False
    )
    
    # 翻译
    translations = ProductTranslationNestedSerializer(many=True, required=False)
    
    # 图片 URL
    cover_image_url = serializers.SerializerMethodField()
    hover_image_url = serializers.SerializerMethodField()
    
    # 变体
    variants = ProductVariantDetailSerializer(many=True, read_only=True)
    
    # 可用的选项类型（用于前端动态生成选项选择器）
    available_options = serializers.SerializerMethodField()
    
    class Meta:
        model = Product
        fields = [
            'id', 'category', 'category_id', 'cover_image', 'hover_image',
            'cover_image_url', 'hover_image_url', 'is_active', 'sort_order',
            'usage', 'tag_new', 'tag_hot', 'tag_featured', 'created_at',
            'updated_at', 'translations', 'variants', 'available_options'
        ]
    
    def get_category(self, obj):
        """获取第一个分类（简化为单分类）"""
        first_cat = obj.categories.first()
        if first_cat:
            return {
                'id': first_cat.id,
                'slug': first_cat.slug
            }
        return None
    
    def get_cover_image_url(self, obj):
        if obj.cover_image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.cover_image.url)
            return obj.cover_image.url
        return None
    
    def get_hover_image_url(self, obj):
        if obj.hover_image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.hover_image.url)
            return obj.hover_image.url
        return None
    
    def get_available_options(self, obj):
        """获取该产品所有变体使用的选项类型"""
        # 获取所有变体的选项值
        option_ids = set()
        for variant in obj.variants.all():
            for option_value in variant.option_values.all():
                option_ids.add(option_value.option.id)
        
        # 获取选项详情
        options = ProductOption.objects.filter(id__in=option_ids, is_active=True)
        serializer = ProductOptionNestedSerializer(options, many=True, context=self.context)
        return serializer.data
    
    def create(self, validated_data):
        """创建产品"""
        translations_data = validated_data.pop('translations', [])
        categories = validated_data.pop('categories', None)
        
        product = Product.objects.create(**validated_data)
        
        # 设置分类（简化为单分类）
        if categories:
            if isinstance(categories, list):
                product.categories.set(categories)
            else:
                product.categories.set([categories])
        
        # 创建翻译
        for translation_data in translations_data:
            ProductTranslation.objects.create(product=product, **translation_data)
        
        return product
    
    def update(self, instance, validated_data):
        """更新产品"""
        translations_data = validated_data.pop('translations', None)
        categories = validated_data.pop('categories', None)
        
        # 更新基本信息
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        
        # 更新分类
        if categories is not None:
            if isinstance(categories, list):
                instance.categories.set(categories)
            else:
                instance.categories.set([categories])
        
        # 更新翻译
        if translations_data is not None:
            instance.translations.all().delete()
            for translation_data in translations_data:
                ProductTranslation.objects.create(product=instance, **translation_data)
        
        return instance


class ProductListNewSerializer(serializers.ModelSerializer):
    """产品列表序列化器（简化版）"""
    category = serializers.SerializerMethodField()
    categories_data = serializers.SerializerMethodField()
    name = serializers.SerializerMethodField()
    translations_data = serializers.SerializerMethodField()
    cover_image_url = serializers.SerializerMethodField()
    variant_count = serializers.SerializerMethodField()
    variants_data = serializers.SerializerMethodField()
    
    class Meta:
        model = Product
        fields = [
            'id', 'category', 'categories_data', 'name', 'translations_data',
            'cover_image_url', 'is_active', 'tag_new', 'tag_hot', 'tag_featured',
            'sort_order', 'variant_count', 'variants_data', 'created_at'
        ]
    
    def get_category(self, obj):
        """获取第一个分类（兼容旧版）"""
        first_cat = obj.categories.first()
        if first_cat:
            return {
                'id': first_cat.id,
                'slug': first_cat.slug
            }
        return None
    
    def get_categories_data(self, obj):
        """获取所有分类信息"""
        categories_data = []
        for cat in obj.categories.all():
            # 获取中文翻译名称
            trans = cat.translations.filter(locale='zh').first()
            name = trans.name if trans else cat.slug
            categories_data.append({
                'id': cat.id,
                'slug': cat.slug,
                'name': name
            })
        return categories_data
    
    def get_name(self, obj):
        """获取中文名称（优先）或英文名称"""
        trans = obj.translations.filter(locale='zh').first()
        if not trans:
            trans = obj.translations.filter(locale='en').first()
        return trans.name if trans else f"Product {obj.id}"
    
    def get_translations_data(self, obj):
        """获取所有翻译"""
        result = {}
        for trans in obj.translations.all():
            result[trans.locale] = {
                'name': trans.name,
                'short_desc': trans.short_desc,
                'rich_desc': trans.rich_desc
            }
        return result
    
    def get_cover_image_url(self, obj):
        if obj.cover_image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.cover_image.url)
            return obj.cover_image.url
        return None
    
    def get_variant_count(self, obj):
        return obj.variants.count()
    
    def get_variants_data(self, obj):
        """返回变体基本信息（用于前端显示数量）"""
        return [{'id': v.id} for v in obj.variants.all()]

